package com.skivingcloud.admin.sys.controller;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.skivingcloud.admin.annotation.ModifyAnnotaionFactory;
import com.skivingcloud.admin.annotation.UserOperateLog;
import com.skivingcloud.admin.sys.entity.SysStation;
import com.skivingcloud.admin.sys.entity.SysStationMenu;
import com.skivingcloud.admin.sys.entity.User;
import com.skivingcloud.admin.sys.service.ISysMenuService;
import com.skivingcloud.admin.sys.service.ISysStationService;
import com.skivingcloud.admin.sys.service.ITenantService;
import com.skivingcloud.admin.utils.UserUtil;
import com.skivingcloud.common.contants.Constant;
import com.skivingcloud.common.exception.BusinessException;
import com.skivingcloud.common.utils.PageUtils;
import com.skivingcloud.common.utils.R;
import com.skivingcloud.common.utils.TreeUtils;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 岗位表 前端控制器
 * </p>
 *
 * @author skivingcloud
 * @since 2022-01-29
 */
@RestController
@RequestMapping("/sys/station")
public class SysStationController {

	private static Logger log = LoggerFactory.getLogger(SysStationController.class);

	@Autowired
	private ISysStationService sysStationService;
	@Autowired
	private ISysMenuService sysMenuService;
	@Autowired
	private ITenantService tenantService;

	/**
	 * 岗位分页查询
	 * 
	 * @param params
	 * @return
	 */
	@PostMapping("/queryList")
	public R queryList(@RequestBody Map<String, Object> params) {
		/*Map<String, Object> params = new HashMap<String, Object>();
		params.put("page", page);
		params.put("limit", limit);
		params.put("dataForm", dataForm);*/
		try {
			PageUtils pages = sysStationService.queryPage(params);
			return R.ok().put("page", pages);
		} catch (JsonParseException e) {
			log.error("无法解析参数", e);
			return R.error("无法解析参数");
		} catch (JsonMappingException e) {
			log.error("无法解析参数", e);
			return R.error("无法解析参数");
		} catch (IOException e) {
			log.error("无法解析参数", e);
			return R.error("无法解析参数");
		} catch (BusinessException e) {
			log.error(e.getMessage(), e);
			return R.error(e.getMessage());
		} catch (Exception e) {
			log.error("查询岗位数据失败", e);
			return R.error("查询数据失败");
		}
	}

	/**
	 * 根据id查询岗位信息
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/info/{id}")
	public R info(@PathVariable("id") String id) throws Exception {
		SysStation councilmbStation = sysStationService.selectById(id);
		return R.ok().put("station", councilmbStation);
	}

	/**
	 * 获取岗位资源树，如果不是超级管理员只返回自己租户的资源
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getResTree")
	@ResponseBody
	public R getResTree(@RequestParam Map<String, Object> params) throws Exception {
		List<String> terminals = new ArrayList<String>();
		User user = UserUtil.getUser();
		List<TreeUtils> list = sysMenuService.gerResTreeByTerminal(terminals, user);
		List<SysStationMenu> asingRes = new ArrayList<SysStationMenu>();
		if (params.get("id") != null && !"".equals(params.get("id"))) {
			asingRes = sysStationService.getResTreeByStationId(params.get("id").toString());
		}
		return R.ok().put("tree", list).put("asingRes", asingRes);
	}

	/**
	 * 保存岗位数据
	 * 
	 * @param station
	 * @return
	 */
	@UserOperateLog(module = "系统功能", methods = "save", description = "保存岗位数据信息")
	@PostMapping("/save")
	public R save(@RequestBody SysStation station) {

		if (station.getId() == null || "".equals(station.getId())) {
			// 新增
			sysStationService.addStation(station, UserUtil.getUser(), station.getResId());
		} else {
			// 修改
			sysStationService.updateStation(station, UserUtil.getUser(), station.getResId());
		}
		return R.ok();
	}

	/**
	 * 
	 * <p>
	 * Title: 保存岗位资源权限
	 * </p>
	 * <p>
	 * Description: 仅设置岗位资源
	 * </p>
	 * 
	 * @param station
	 * @return
	 */
	@UserOperateLog(module = "系统功能", methods = "saveStationRes", description = "设置岗位资源权限")
	@PostMapping("/saveStationRes")
	public R saveStationRes(@RequestBody SysStation station) {
		try {
			sysStationService.saveStationRes(station.getId(), station.getResId(), UserUtil.getUser());
			return R.ok();
		} catch (Exception e) {
			log.error("设置资源权限失败", e);
			return R.error(1, "设置资源权限失败");
		}
	}

	/**
	 * 删除岗位信息
	 */
	@UserOperateLog(module = "系统功能", methods = "delete", description = "删除岗位信息")
	@PostMapping("/delete")
	public R delete(@RequestBody String[] ids) throws Exception {
		try {
			sysStationService.deleteBatch(ids);
			return R.ok();
		} catch (Exception e) {
			log.error("删除岗位失败", e);
			return R.error("删除岗位失败");
		}
	}

	/**
	 * 批量删除岗位的资源权限
	 * 
	 * @param ids
	 * @return
	 * @throws Exception
	 */
	@UserOperateLog(module = "系统功能", methods = "deleteStationRes", description = "批量删除岗位的资源权限", functionNo = "101042")
	@PostMapping("/deleteStationRes")
	public R deleteStationRes(@RequestBody String[] ids) throws Exception {
		try {
			sysStationService.deleteStationRes(ids, UserUtil.getUser());
			// 给日志注解传入业务id
			ModifyAnnotaionFactory.newInstance().ModifyAnnotation(getClass(), UserOperateLog.class, "deleteStationRes",
					"bussid", ids.toString(), ids.getClass());
			return R.ok();
		} catch (Exception e) {
			log.error("删除岗位资源权限失败", e);
			return R.error("删除岗位资源权限失败");
		}
	}

	/**
	 * 获取树形机构
	 * 
	 * @param tenantId 租户id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/treeStationList/{tenantId}")
	@ResponseBody
	public List<TreeUtils> treeStationList(@PathVariable("tenantId") String tenantId) throws Exception {
		return sysStationService.getAllStationTreeUtilsByTenantId(tenantId);

	}

	/**
	 * 获取树形机构，icon属性存的是id
	 * 
	 * @param tenantId 租户id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/treeStationListIconFnId/{tenantId}")
	@ResponseBody
	public List<TreeUtils> treeStationListIconFnId(@PathVariable("tenantId") String tenantId) throws Exception {
		return sysStationService.getAllStationTreeUtilsIconFnIdByTenantId(tenantId);

	}

	/**
	 * 获取岗位资源树，如果不是超级管理员只返回自己租户的资源
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getTenantStationResTree")
	@ResponseBody
	public R getTenantStationResTree(@RequestParam Map<String, Object> params) throws Exception {
		// List<String> terminals = new ArrayList<String>();
		User user = UserUtil.getUser();
		// List<TreeUtils> list = sysMenuService.gerResTreeByTerminal(terminals, user);
		String tenantId = params.get("tenantId") == null ? null : params.get("tenantId").toString();
		if (!user.getTenantId().equals(Constant.SUPER_ADMIN_TENANTID)) {
			tenantId = user.getTenantId();
		}
		if (tenantId == null) {
			return R.ok();
		}
		List<TreeUtils> list = tenantService.getTenantRoleResTree(tenantId);
		List<SysStationMenu> asingRes = new ArrayList<SysStationMenu>();
		if (params.get("id") != null && !"".equals(params.get("id"))) {
			asingRes = sysStationService.getResTreeByStationId(params.get("id").toString());
		}
		return R.ok().put("tree", list).put("asingRes", asingRes);
	}
}
